package priv.pfz.basedao;

import com.google.common.collect.Iterables;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.Map;

/**
 * @author yyjxp
 * 2024/1/28 21:49
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Utils {
    public static <T> T checkNotNull(T param, String pattern, Object... arguments) {
        if (param == null) {
            throw new RuntimeException(MessageFormat.format(pattern, arguments));
        }
        return param;
    }

    public static void checkNotEmpty(Iterable<?> param, String pattern, Object... arguments) {
        if (param == null || Iterables.isEmpty(param)) {
            throw new RuntimeException(MessageFormat.format(pattern, arguments));
        }
    }

    public static void checkNotEmpty(Map<?, ?> param, String pattern, Object... arguments) {
        if (param == null || param.isEmpty()) {
            throw new RuntimeException(MessageFormat.format(pattern, arguments));
        }
    }

    public static void checkArgument(boolean param, String pattern, Object... arguments) {
        if (!param) {
            throw new RuntimeException(MessageFormat.format(pattern, arguments));
        }
    }

    public static void checkNotBlank(String param, String pattern, Object... arguments) {
        if (StringUtils.isBlank(param)) {
            throw new RuntimeException(MessageFormat.format(pattern, arguments));
        }
    }

    public static String getFilename(String path, String filename) {
        if (path.endsWith("/") || path.endsWith("\\")) {
            return path + filename;
        } else {
            return path + "/" + filename;
        }
    }

    public static Object getFieldValue(Field field, Object object) {
        try {
            return field.get(object);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public static Object getFieldValue(Method method, Object object) {
        try {
            return method.invoke(object);
        } catch (InvocationTargetException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
